package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserServer;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Service
public class UserServerImpl implements UserServer {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    JwtProperties jwtProperties;

    @Autowired
    private UserMapper userMapper;

    public static final String WeXinLoginUrl = "https://api.weixin.qq.com/sns/jscode2session";


    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {

        //1.当拿到客户端发起的code后，首先先得到配置的WeChat配置的appid和 secret
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type", "authorization_code");
        //2.然后向微信接口发送Get请求（数据需要是JSON格式）
        String resultJson = HttpClientUtil.doGet(WeXinLoginUrl, map);

        //3.如果openid为空，则说明没有登录成功，返回给前端用户信息（public static final String LOGIN_FAILED = "登录失败";）
        JSONObject jsonObject = JSONObject.parseObject(resultJson);
        String openid = jsonObject.getString("openid");
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //4.然后判断是新用户还是旧用户（如果是新那么就执行update把openid加入用户表中，如果是老用户，那么就返回给前端openid）
        User user = userMapper.getByOpenid(openid);
        if (user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        //生成token
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(),claims);
        //6.然后根据返回的user的ID并创建token然后合并到返回的VO对象中
        UserLoginVO userLoginVO = new UserLoginVO(user.getId(), openid, token);
        return userLoginVO;
    }
}
